package com.hxkcloud.patient.fragments;

import android.annotation.SuppressLint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.adapter.DiscoverPatientsAdapter;
import com.hxkcloud.patient.adapter.GroupHorizontalAdapter;
import com.hxkcloud.patient.beans.DoctorGroupBean;
import com.hxkcloud.patient.beans.PatientBean;
import com.hxkcloud.patient.beans.PatientWholeBean;
import com.hxkcloud.patient.dborm.DoctorGroupDao;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.views.ListDividerItemDecoration;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullableRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by william_sun on 2016-07-09.
 * Description:发现页下方患者列表
 */
@SuppressLint("ValidFragment")
public class DiscoverPatientFragment extends BaseFragment implements PullToRefreshLayout.OnRefreshListener, View.OnClickListener {

    private View view;
    private int pType = 0;//0未管理 1已管理
    private PullToRefreshLayout refreshLayout;
    private PullableRecyclerView recycleView;
//    private RecyclerView recyclerView;

    private ArrayList<PatientBean> patients;
    private DiscoverPatientsAdapter adapter;
    private int totalCount = 0;

    private int pageIndex = 1;
    private int pageSize = 15;
    private int loadmoreType = 0;//0第一次获取1刷新2更多

//    private PopupWindow popupBind;//绑定提示
//    private TextView tv_popupbind_title;
//    private TextView tv_popupbind_cancel;
//    private TextView tv_popupbind_sure;

    private PopupWindow popupGroupBind;
    private TextView tv_popupgroupbind_title;
    private RecyclerView rv_popupgroupbind;
    private TextView tv_popupgroupbind_cancel;
    private TextView tv_popupgroupbind_sure;
    private List<DoctorGroupBean> groups;
    private GroupHorizontalAdapter groupAdapter;

    private int patientBindP;//要执行绑定操作的患者position

    private discoverPatientRefreshListener refreshListener;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_GETDEPARTMENTPATIENTLIST_SUCCESS:
                if (loadmoreType == 1) {
                    refreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    patients.clear();
                } else if (loadmoreType == 2) {
                    refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }
                if (msg.obj != null) {
                    PatientWholeBean patientWhole = (PatientWholeBean) msg.obj;
                    totalCount = patientWhole.getTotalCount();
                    if (patientWhole.getList() != null && patientWhole.getList().size() > 0) {
                        patients.addAll(patientWhole.getList());
                        adapter.setData(patients);
                    }
                } else {
                    toastMsg(R.string.departmentpatientsgetfail);
                }
                break;
            case MessageCode.NETWORKCODE_GETDEPARTMENTPATIENTLIST_FAILURE:
                if (loadmoreType == 1) {
                    refreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                } else if (loadmoreType == 2) {
                    refreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
                if (msg.obj != null) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.departmentpatientsgetfail);
                }
                break;
            case MessageCode.NETWORKCODE_CONNECT_ERROR:
                if (loadmoreType == 1) {
                    refreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                } else if (loadmoreType == 2) {
                    refreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
                break;
            case MessageCode.NETWORKCODE_PATIENTBINDING_SUCCESS:
                toastMsg((String) msg.obj);

//                PatientBean patientBind = patients.get(patientBindP);
//                String groupId = "";
//                for (DoctorGroupBean group : groups) {
//                    if (group.isSelect()) {
//                        groupId = group.getGroupId();
//                    }
//                }
//                YiJiaHuNetWorkUtils.userJoinDoctorGroup(groupId, patientBind.getPatientId(), handler);


                refreshListener.onAllRefresh();

                //管理页排序
                YiJiaHuNetWorkUtils.userTalking(patients.get(patientBindP).getPatientId(), handler);
                break;
            case MessageCode.NETWORKCODE_PATIENTBINDING_FAILURE:
                if (msg.obj != null) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.bindfail);
                }
                break;
            case MessageCode.NETWORKCODE_USERJOINDOCTORGROUP_SUCCESS:

                break;
            case MessageCode.NETWORKCODE_USERJOINDOCTORGROUP_FAILURE:
                if (msg.obj != null) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.userjoingroupfail);
                }
                break;
        }
    }

    public DiscoverPatientFragment(int type, discoverPatientRefreshListener listener) {
        this.pType = type;
        this.refreshListener = listener;

        patients = new ArrayList<>();
        pageIndex = 1;

    }

    public void refresh() {
        loading();
        loadmoreType = 1;
        pageIndex = 1;
        YiJiaHuNetWorkUtils.getPatientList(loginInfo.getDepartmentId(), pType, pageIndex, pageSize, handler);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_discoverpatient, null);
        initView();
        initData();
        initPopup();
        return view;
    }

    @Override
    protected void initView() {
        refreshLayout = (PullToRefreshLayout) view.findViewById(R.id.refreshlayout_discoverpatient);
        recycleView = (PullableRecyclerView) view.findViewById(R.id.recyclerview_discoverpatient);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(mLayoutManager);
        ListDividerItemDecoration itemDecoration = new ListDividerItemDecoration(
                mContext, ListDividerItemDecoration.VERTICAL_LIST);
        recycleView.addItemDecoration(itemDecoration);
        refreshLayout.setOnRefreshListener(this);

        adapter = new DiscoverPatientsAdapter(mContext, pType, patients, screenWidth, new DiscoverPatientsAdapter.patientBindListener() {
            @Override
            public void onBind(int position) {
                patientBindP = position;
                PatientBean patientBind = patients.get(position);
//                tv_popupbind_title.setText("绑定后，您将成为" + patientBind.getName() + "的责任护士");
//                popupBind.showAtLocation(view, Gravity.CENTER, 0, 0);
                for (DoctorGroupBean group : groups) {
                    if (group.getGroupId().equals(patientBind.getGroupId())) {
                        group.setIsSelect(true);
                    } else {
                        group.setIsSelect(false);
                    }
                }
                groupAdapter.setDatas(groups);
                popupGroupBind.showAtLocation(view, Gravity.CENTER, 0, 0);
                BrightnessUtils.lightOff(activity);
            }
        });
        recycleView.setAdapter(adapter);
    }

    private void initPopup() {
//        popupBind = new PopupWindow(mContext);
//        View viewNotice = LayoutInflater.from(mContext).inflate(R.layout.popup_easynotice, null);
//        popupBind.setContentView(viewNotice);
//
//        popupBind.setWidth((int) (screenWidth * 0.7));
//        popupBind.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//        popupBind.setFocusable(true);
//        popupBind.setTouchable(true);
//        popupBind.setOutsideTouchable(true);
//        popupBind.setBackgroundDrawable(new ColorDrawable(0x00000000));
//        popupBind.setAnimationStyle(R.style.popupwindow_anim_alpha);
//
//        tv_popupbind_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice_title);
//        tv_popupbind_cancel = (TextView) viewNotice.findViewById(R.id.tv_easynotice_cancel);
//        tv_popupbind_sure = (TextView) viewNotice.findViewById(R.id.tv_easynotice_func);
//
//        tv_popupbind_cancel.setOnClickListener(this);
//        tv_popupbind_sure.setOnClickListener(this);
//
//        popupBind.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                BrightnessUtils.lightOn(activity);
//            }
//        });

        popupGroupBind = new PopupWindow(mContext);
        View viewBind = LayoutInflater.from(mContext).inflate(R.layout.popup_doctorgroup, null);
        popupGroupBind.setContentView(viewBind);

        popupGroupBind.setWidth((int) (screenWidth * 0.7));
        popupGroupBind.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupGroupBind.setFocusable(true);
        popupGroupBind.setTouchable(true);
        popupGroupBind.setOutsideTouchable(true);
        popupGroupBind.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupGroupBind.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_popupgroupbind_title = (TextView) viewBind.findViewById(R.id.tv_doctorgroup_title);
        rv_popupgroupbind = (RecyclerView) viewBind.findViewById(R.id.rv_doctorgroup);
        tv_popupgroupbind_cancel = (TextView) viewBind.findViewById(R.id.tv_doctorgroup_cancel);
        tv_popupgroupbind_sure = (TextView) viewBind.findViewById(R.id.tv_doctorgroup_func);

        tv_popupgroupbind_title.setText(R.string.choosepatientbelonggroup);
        tv_popupgroupbind_cancel.setOnClickListener(this);
        tv_popupgroupbind_sure.setOnClickListener(this);

        popupGroupBind.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(activity);
            }
        });

        groups = new ArrayList<>();
        DoctorGroupDao doctorGroupDao = new DoctorGroupDao(mContext);
        groups = doctorGroupDao.getGroup();
        groupAdapter = new GroupHorizontalAdapter(mContext, groups, new GroupHorizontalAdapter.onGroupHorizontalClickListener() {
            @Override
            public void onClick(int position) {
                for (DoctorGroupBean group : groups) {
                    group.setIsSelect(false);
                }
                groups.get(position).setIsSelect(true);
                groupAdapter.setDatas(groups);
            }
        }, screenWidth);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_popupgroupbind.setLayoutManager(mLayoutManager);
        rv_popupgroupbind.setAdapter(groupAdapter);
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        if (patients == null || patients.size() == 0) {
            YiJiaHuNetWorkUtils.getPatientList(loginInfo.getDepartmentId(), pType, pageIndex, pageSize, handler);
        }
    }

    public void setRefreshble(boolean isready, int type) {
        if (isready) {
            if (type == 0) {
//                plv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
//                refreshLayout.setCanPull(true, false);
                recycleView.setCanRefresh(true);
                recycleView.setCanLoadMore(false);
            } else {
//                plv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
//                refreshLayout.setCanPull(false, true);
                recycleView.setCanRefresh(false);
                recycleView.setCanLoadMore(true);
            }
        } else {
//            plv.setMode(PullToRefreshBase.Mode.DISABLED);
//            refreshLayout.setCanPull(false, false);
            recycleView.setCanRefresh(false);
            recycleView.setCanLoadMore(false);
        }

    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
//        loadmoreType = 1;
//        currentPage = 0;
//        adapter.cleanData();
//        getData();
//        refresh_view.refreshFinish(PullToRefreshLayout.SUCCEED);
        loading();
        loadmoreType = 1;
        pageIndex = 1;
        YiJiaHuNetWorkUtils.getPatientList(loginInfo.getDepartmentId(), pType, pageIndex, pageSize, handler);
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
//        loadmoreType = 2;
//        currentPage++;
//        getData();
//        refresh_view.loadmoreFinish(PullToRefreshLayout.SUCCEED);
        if (totalCount <= patients.size()) {
            toastMsg(R.string.nomore);
            refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
        } else {
            loading();
            loadmoreType = 2;
            pageIndex++;
            YiJiaHuNetWorkUtils.getPatientList(loginInfo.getDepartmentId(), pType, pageIndex, pageSize, handler);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.tv_easynotice_cancel:
//                popupBind.dismiss();
//                break;
//            case R.id.tv_easynotice_func:
//                popupBind.dismiss();
//                loading();
//                PatientBean patientBind = patients.get(patientBindP);
//                YiJiaHuNetWorkUtils.patientBinding(patientBind.getPatientId(), handler);
//                break;
            case R.id.tv_doctorgroup_cancel:
                popupGroupBind.dismiss();
                break;
            case R.id.tv_doctorgroup_func:
                String groupId = "";
                for (DoctorGroupBean group : groups) {
                    if (group.isSelect()) {
                        groupId = group.getGroupId();
                    }
                }
                if (TextUtils.isEmpty(groupId)) {
                    toastMsg(R.string.choosepatientbelonggroup);
                    return;
                }

                popupGroupBind.dismiss();
                loading();
                PatientBean patientBind = patients.get(patientBindP);
                YiJiaHuNetWorkUtils.patientBinding(patientBind.getPatientId(), groupId, handler);
//                YiJiaHuNetWorkUtils.userJoinDoctorGroup(groupId, patientBind.getPatientId(), handler);
                break;
        }
    }

    public interface discoverPatientRefreshListener {
        void onAllRefresh();
    }

    public void setDoctorGroup(List<DoctorGroupBean> gs) {
        if (gs != null && gs.size() > 0) {
            this.groups = gs;
            for (DoctorGroupBean group : groups) {
                group.setIsSelect(false);
            }

            groupAdapter = new GroupHorizontalAdapter(mContext, groups, new GroupHorizontalAdapter.onGroupHorizontalClickListener() {
                @Override
                public void onClick(int position) {
                    for (DoctorGroupBean group : groups) {
                        group.setIsSelect(false);
                    }
                    groups.get(position).setIsSelect(true);
                    groupAdapter.setDatas(groups);
                }
            }, screenWidth);
            rv_popupgroupbind.setAdapter(groupAdapter);

        }
    }
}
